package com.hellloop.pim.alphabeat.network;

import java.io.*;
import java.net.*;
import java.util.*;


public class PIMClientConnectionThread extends Thread {

	private PIMClient client;

	private Socket sock;

	private PrintWriter writer;

	private BufferedReader reader;

	private List<PIMMessage> recMessageQueue;

	public PIMClientConnectionThread(PIMClient client, String host, int port,
			List<PIMMessage> recMessageQueue) throws UnknownHostException,
			IOException {
		this.client = client;
		this.sock = new Socket(host, port);
		writer = new PrintWriter(sock.getOutputStream(), true);
		reader = new BufferedReader(
				new InputStreamReader(sock.getInputStream()));

		// Verify that the receive message queue is not null
		if (recMessageQueue == null) {
			throw new IllegalArgumentException(
					"The receive message queue cannot be null");
		}

		this.recMessageQueue = recMessageQueue;
		this.start();
		System.out.println("ClientConnection: " + this.sock);
	}

	public void run() {

		while (true) {
			try {
				receiveMessage();
			} catch (IOException e) {
				// Cannot read message from server
				e.printStackTrace();
				break;
			}
		}

	}

	public void sendMessage(PIMMessage pm) {
		String message = pm.toString();
		writer.println(message);
	}

	void receiveMessage() throws IOException {
		String line;
		if ((line = reader.readLine()) != null) {
			recMessageQueue.add(PIMMessage.decodeMessage(line));
		}
	}

	void closeConnection() throws IOException {
		writer.close();
		reader.close();
		sock.close();
	}

}
